//
//
//

#import "NativeSdkHelper.h"
#import "IOSKeyChain.h"
#import <sys/utsname.h>
#include <iostream>
#import <sys/utsname.h>
#include "cocos2d.h"
#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"


#import "AVFoundation/AVFoundation.h"


#import<CoreLocation/CoreLocation.h>
#import "YY_ImagePicker.h"

#import <SDPTLib/SDPTFramework.h>




@interface NativeSdkHelper()<CLLocationManagerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(strong, nonatomic) NSString* tempImgPath;
@property(strong, nonatomic) CLLocationManager *locationManager;

@end


@implementation NativeSdkHelper


static NativeSdkHelper *_sharedInstance = nil;

#define UQID_KEY @"com.jhao.dajiale"


//单例
+(instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[NativeSdkHelper alloc] init];
    });
    return _sharedInstance;
}

-(UIViewController *)getViewController{
    UIViewController* ctrol;
    if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0){
        // warning: addSubView doesn't work on iOS6
        NSArray* array=[[UIApplication sharedApplication]windows];
        UIWindow* win=[array objectAtIndex:0];
        UIView* ui=[[win subviews] objectAtIndex:0];
        ctrol =(UIViewController*)[ui nextResponder];
    }else{
        ctrol=[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    return ctrol;
}


-(BOOL)isEmptyString:(NSString *)string {
    if (string) {
        if (![string isKindOfClass:[NSString class]]) {
            NSLog(@"不是字符串类型");
            return YES;
        }
        NSString *tempStr = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        return [tempStr isEqualToString:@""];
    }
    return YES;
}

//json字符串 转 dic
-(NSDictionary* )transferToDictionaryWithJsonString:(NSString* )jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error = nil;
    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        return nil;
    }
    return dic;
}

//dic 转 jsonString
-(NSString *)transferToJsonStringWithDictionary:(NSDictionary *)dic {
    if (dic == nil) {
        return nil;
    }
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
    if (!jsonData) {
        NSLog(@"%@",error);
        return nil;
    }
    NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}


//回调给研发，放主线程
-(void)CallbackToJSWithMethodName:(NSString*)name ret:(id )retObj {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString* retStr = retObj;
        if ([self isEmptyString:retStr]) {
            //加个判断，防止空字符串闪退
            retStr = @"";
        }
        
        //转义替换
        NSMutableString *mutStr = [NSMutableString stringWithString:retStr];
        NSRange range = NSMakeRange(0, mutStr.length);
        [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range];
        range = NSMakeRange(0, mutStr.length);
        [mutStr replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:range];
        NSString* etc_result = [NSString stringWithFormat:@"%@", mutStr];
        
//        //回调给cocos
        NSString* funcNameStr = [NSString stringWithFormat:@"NativeSdkHelper.%@", name];
        std::string funcName = [funcNameStr UTF8String];
        std::string param = [etc_result UTF8String];
        std::string jsCallStr = funcName+"('"+param+"');";
            
//        std::string jsCallStr = cc::StringUtils::format("%s('%s');", funcName.c_str(), param.c_str());
        se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());
        
    });
}

//初始化
+(void)sdkInit:(NSString* )jsonStr{
    
}

//保持屏幕常亮
+(void)keyScreenLight:(NSString* )jsonStr{
    NSLog(@"NativeSdkHelper.keyScreenLight=====");
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

+(void)copy:(NSString*)str
{
    NSLog(@"NativeSdkHelper.copy :%@",str);
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:str];
}

+(void)vibrate:(NSString* )jsonStr{
    NSLog(@"NativeSdkHelper.vibrate==========");
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

+ (NSString *)getUDID:(NSString* )jsonStr{
    NSString *deviceUDID = [self getOnlyId];
    NSLog(@"NativeSdkHelper.getUDID==========%@", deviceUDID);
    return deviceUDID;
}


+ (NSString *)getOnlyId{
    //从本地沙盒取
    NSString *uqid = [[NSUserDefaults standardUserDefaults] objectForKey:UQID_KEY];
    NSLog(@"getOnlyId==========%@", uqid);
    if (!uqid) {
        //从keychain取
        uqid = (NSString *)[IOSKeyChain readObjectForKey:UQID_KEY];
        NSLog(@"getUQID2222==========%@", uqid);
        if (uqid) {
            [[NSUserDefaults standardUserDefaults] setObject:uqid forKey:UQID_KEY];
            [[NSUserDefaults standardUserDefaults] synchronize];
        } else {
            //从pasteboard取
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            id data = [pasteboard dataForPasteboardType:UQID_KEY];
            if (data) {
                uqid = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            }
            NSLog(@"getUQID3333==========%@", uqid);
            if (uqid) {
                [[NSUserDefaults standardUserDefaults] setObject:uqid forKey:UQID_KEY];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [IOSKeyChain saveObject:uqid forKey:UQID_KEY];
            } else {
                //获取uuid
                uqid = [[NSUUID UUID] UUIDString];
                NSLog(@"getUQID4444==========%@", uqid);
                [[NSUserDefaults standardUserDefaults] setObject:uqid forKey:UQID_KEY];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [IOSKeyChain saveObject:uqid forKey:UQID_KEY];
                
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                NSData *data = [uqid dataUsingEncoding:NSUTF8StringEncoding];
                [pasteboard setData:data forPasteboardType:UQID_KEY];
            }
        }
    }
    return uqid;
}

+(NSString *)getSystemVersion:(NSString *)jsonStr{
    NSString *sysVersion = [[UIDevice currentDevice] systemVersion];
    NSLog(@"NativeSdkHelper.getSystemVersion :%@",sysVersion);
    return sysVersion;
}


+(NSString *)getBundleName:(NSString* )jsonStr{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *packageName = [infoDictionary objectForKey:@"CFBundleIdentifier"];
    NSLog(@"NativeSdkHelper.getBundleName :%@",packageName);
    return packageName;
}

+(NSString *)getAppVersion:(NSString*) jsonStr{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSLog(@"NativeSdkHelper.getAppVersion :%@",app_Version);
    return app_Version;
}

////获取手机版本
+(NSString *)getIphoneType:(NSString*) inputStr{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine
                                            encoding:NSUTF8StringEncoding];
    NSLog(@"NativeSdkHelper.getIphoneType :%@",platform);
//
    return  platform;
}


+(void)getLocation:(NSString* )jsonStr{
    NSLog(@"getLocation====");
    [NativeSdkHelper sharedInstance].locationManager = [[CLLocationManager alloc] init];
    [NativeSdkHelper sharedInstance].locationManager.delegate =  [NativeSdkHelper sharedInstance];
    [[NativeSdkHelper sharedInstance].locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8){
        //只有在前台开始定位
        [[NativeSdkHelper sharedInstance].locationManager requestWhenInUseAuthorization];
    }
    [[NativeSdkHelper sharedInstance].locationManager startUpdatingLocation];
    
}



//23.361933,113.281694
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    if(locations && [locations count] > 0){
        CLLocation *newLocation = locations[0];
        [manager stopUpdatingLocation];
        CLGeocoder *gencoder = [[CLGeocoder alloc] init];
        [gencoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if(placemarks && [placemarks count]>0){
                CLLocationDegrees latitude = newLocation.coordinate.latitude;
                CLLocationDegrees longitude = newLocation.coordinate.longitude;
                NSString *address = @"火星";
                for(CLPlacemark *place in placemarks){
                    if(place.locality.length > 0){
                        NSLog(@"获取到位置==1111==%@,%@,%@,%@,%@", place.locality,place.subLocality, place.thoroughfare,place.subThoroughfare, place.description);
                        
                        address = [NSString stringWithFormat:@"%@%@%@", place.locality,place.subLocality, place.thoroughfare];
                    }
                }
                NSLog(@"获取到位置====%f,%f", latitude, longitude);
                NSLog(@"获取到位置==222==%@", address);
                
                NSString *result = [NSString stringWithFormat:@"%f,%f|%@", latitude,longitude, address];
                NSLog(@"获取到位置==333==%@", result);
//                std::string result_cstr = [result UTF8String];
                [[NativeSdkHelper sharedInstance]  CallbackToJSWithMethodName:@"setLocation" ret:result];
                
            }
        }];
    }
}

///*选择图片写入指定全路径,建议使用jpg格式xxx/xxx/xx.jpg*/
//+(int)openAlbumToWriteWithWritePath:(NSString* )imageWritePath{
//    NSLog(@"openAlbumToWriteWithWritePath--imageWritePath--%@", imageWritePath);
//    [NativeSdkHelper sharedInstance].tempImgPath = imageWritePath;
//    NSLog(@"openAlbumToWriteWithWritePath--tempImgPath--%@", [NativeSdkHelper sharedInstance].tempImgPath);
//    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//    [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//    [imagePicker setDelegate:[NativeSdkHelper sharedInstance]];
//
//    UIViewController *viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
//    if (viewController != nil){
//        [viewController presentViewController:imagePicker animated:true completion:nil];
//    }
//    return 1;
//};

/*选择图片写入指定全路径,建议使用jpg格式xxx/xxx/xx.jpg*/
+(int)openAlbumToWriteWithWritePath:(NSString* )jsonStr{
    NSLog(@"openAlbumToWriteWithWritePath--imageWritePath--%@", jsonStr);
    
    NSDictionary* dic = [[NativeSdkHelper sharedInstance] transferToDictionaryWithJsonString:jsonStr];
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
       NSLog(@"%s：dic is null", __FUNCTION__);
       return 0;
    }
    NSString* width =[dic objectForKey:@"clipX"];
    NSString* height =[dic objectForKey:@"clipY"];
    NSInteger widthNum = [width integerValue];
    NSInteger heightNum = [height integerValue];
    widthNum = 150;
    heightNum = 150;
    NSLog(@"openAlbumToWriteWithWritePath--11->>>%@,%@", width, height);
    
    [[YY_ImagePicker getInstence] pickFromPhoto:widthNum :heightNum completion:^(NSString * bigPath, NSString * smallPath) {
        NSLog(@"选择图片成功--11->>>%@", bigPath);
        NSLog(@"选择图片成功--22->>>%@", smallPath);
//        std::string nowPhotoPath = [smallPath UTF8String];
        
        [[NativeSdkHelper sharedInstance]  CallbackToJSWithMethodName:@"onSelectPhoto_callback" ret:smallPath ];
    }];

    return 1;
};


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    NSLog(@"选择图片成功--->>>%@", type);
    if ([type isEqualToString:@"public.image"]) {
        //            NSURL *tempDir = [NSURL URLWithString:NSTemporaryDirectory()];
        //            NSURL *bigPath = [tempDir URLByAppendingPathComponent:@"avatar_big.jpg"];
        NSURL * bigPath = [NSURL URLWithString:[NativeSdkHelper sharedInstance].tempImgPath];
        NSLog(@"保存图片成功--222->>>%@", bigPath);
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        std::string callFunStr = "";
        @try {
            [data writeToURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@",bigPath.absoluteString]] options:NSDataWritingAtomic error:nil];
//            std::string nowPhotoPath = [[NativeSdkHelper sharedInstance].tempImgPath UTF8String];

            [[NativeSdkHelper sharedInstance]  CallbackToJSWithMethodName:@"onSelectPhoto_callback" ret:[NativeSdkHelper sharedInstance].tempImgPath ];
            
        } @catch (NSException *exception) {
            //            callFunStr = "cc.vv.anysdkMgr..finishWriteAlbum('保存图片失败')";
            NSLog(@"保存图片失败-->>>");
        }
        
    }
}


+(void)setFileToLocal:(NSString*)path{
    NSLog(@"setFileToLocal==%@", path);
//    @try {
        UIImage *image = [UIImage imageWithContentsOfFile:path]; // 取得图片
        UIImageWriteToSavedPhotosAlbum(image, [NativeSdkHelper sharedInstance], @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//    } @catch (NSException *exception) {
//        NSLog(@"保存图片错误");
//    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error != nil) {
        NSLog(@"Couldn't save image");
    } else {
        NSLog(@"Saved image");
    }
}

@end
